/**
*  @author: yaoyuan
*  @copyright: kopanya.com
*  @version: 1.0
*  Description: mongoPool    创建数据库连接池以及实现方法 
*  created: 2014.05.14
*  updated: 2014.05.19
*  Update Logs:
*               [1] 创建对象
*               [2] ES6语化
**/
import mongoose from 'mongoose';
import config from './config';

let connectionURL = "";

var MongoDb = {
    getConnecting(options){
        _U.log('Ready to use MongoDB');
        connectionURL = `mongodb://${config.host}/${config.db}`;
        var db = mongoose.connect(connectionURL);
        return db;
    },
    connection(options){
        _U.log('Ready to use MongoDB');
        if(options) {
            this.debug(options.debug);
        }
        connectionURL = `mongodb://${config.host}/${config.db}`;
        var db = mongoose.connect(connectionURL);
        return db;
    },
    interval(time){

   //     setTimeout(this.connection, time);
    },
    debug(is){
        is = is  || false;
        _U.log('start debug model!!!(', is, ')');
        mongoose.set('debug', is);
        return this;
    }
}

export default MongoDb;

// 连接数据库绑定事件
// 当建立成功
mongoose.connection.on('connected', () => {
    _U.success(`Mongoose default connection open to ${connectionURL}`);
});

// 如果出现连接错误事件处理
mongoose.connection.on('error', (err) => {
    _U.error(`Mongoose default connection error: ${err}`);
    const c = a + b;
    a = b;
    b = c;
    MongoDb.interval(b);
});

// 当断开连接事件处理
mongoose.connection.on('disconnected',() => {
    _U.def('Mongoose default connection disconnected');
});

// 如果系统进程关闭，关闭数据库连接
process.on('SIGINT', function() {
    mongoose.connection.close(() => {
        _U.def('Mongoose default connection disconnected through app termination');
        process.exit(0);
    });
});
